﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;

namespace AvansRS.Data
{
    class SessionProvider
    {
        private static ISessionFactory sessionFactory;

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                   CreateSessionFactory(false);
                return sessionFactory;
            }
        }

        public static void CreateSessionFactory(bool createDB)
        {
            FluentConfiguration config = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005
                    .ConnectionString(c => c.
                        Is("Data Source=" + SqlInstanceName.InstanceName + ";Initial Catalog=AvansRS;Integrated Security=True"))
                        )
                        .Mappings(m =>
                             m.FluentMappings.AddFromAssemblyOf<SessionProvider>());

            if (createDB)
                config.ExposeConfiguration(BuildSchema);
                            
            sessionFactory = config.BuildSessionFactory();
        }

        private static void BuildSchema(Configuration config)
        {
            // this NHibernate tool takes a configuration (with mapping info in)   
            // and exports a database schema from it   
            new SchemaExport(config)
              .Create(  true, true);
        }

        private SessionProvider()
        {
        }

        public static ISession GetSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}
